import requests
import json
from interview_test_questions.about_one_question.settings import DEEPSEEK_API_KEY, API_URL


def deepseek_call(prompt: str, func_type: str, stream=False) -> str:
    """调用DeepSeek大模型实现具体功能（支持流式响应）"""
    # 根据功能类型构造不同prompt（关键逻辑）
    if func_type == "translate_zh_to_en":
        system_prompt = "你是专业的翻译官，将用户输入的中文准确翻译成英文"
    elif func_type == "translate_en_to_zh":
        system_prompt = "你是专业的翻译官，将用户输入的英文准确翻译成中文"
    elif func_type == "summarize":
        system_prompt = "你是优秀的内容总结者，用简洁的语言概括用户输入的文本核心"
    else:
        raise ValueError(f"不支持的功能类型：{func_type}")

    # 构造DeepSeek API请求体
    payload = {
        "model": "deepseek-llm-7b",  # 使用7B对话模型，本地配置不够部署的是1.5b，不大聪明
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ],
        "max_tokens": 512,
        "temperature": 0.7,
        "stream": stream
    }

    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }

    response = requests.post(API_URL, json=payload, headers=headers, stream=stream)
    response.raise_for_status()  # 抛出HTTP错误

    if not stream:
        # 非流式：返回完整结果
        return response.json()["choices"][0]["message"]["content"]
    else:
        # 流式：返回生成器逐块输出
        def stream_generator():
            for line in response.iter_lines():
                if line:  # 跳过空行
                    try:
                        chunk = json.loads(line.decode("utf-8"))
                        content = chunk.get("choices", [{}])[0].get("message", {}).get("content", "")
                        if content:
                            yield content
                    except json.JSONDecodeError:
                        continue  # 忽略解析失败的块
        return stream_generator()